<!-- 本地用户 -->
<template>
  <div>
    <CommonSearch @search="query" @reset="reset">
      <el-col :span="8">
        <el-form-item label="用户名称">
          <el-input
            v-model="queryParams.condition.accountName"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="手机号">
          <el-input
            v-model="queryParams.condition.phone"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="queryParams.condition.createdTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%; height: 33px"
            @change="(date) => timeChange(date, queryParams.condition)"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="所属角色" prop="roleId">
          <DictSelect
            v-model="queryParams.condition.roleId"
            :url="api.queryRoleList"
            cacheValue="roleIdList"
            multiple
            placeholder="请选择"
            :valueFormat="
              (item) => {
                return item.roleId;
              }
            "
            :labelFormat="
              (item) => {
                return item.roleName;
              }
            "
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="状态">
          <DictSelect
            v-model="queryParams.condition.status"
            :defaultOptions="options.status"
            placeholder="请选择状态"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </CommonSearch>

    <el-row class="cardMiniBar">
      <el-col :span="24">
        <div class="fr">
          <el-button @click="openUnionRole" size="small">关联角色</el-button>
          <el-button type="primary" @click="add" size="small">新增</el-button>
          <el-button @click="handlerDelete()" size="small">批量删除</el-button>
          <el-button type="primary" @click="exportExcel()" size="small"
            >导出</el-button
          >
        </div>
      </el-col>
    </el-row>

    <div class="cardBody">
      <edu-table
        ref="mainTable"
        :data="tableList"
        :pageSize="queryParams.pageSize"
        :pageNum="queryParams.pageNum"
        :total="queryParams.total"
        @page-change="handleCurrentChange"
        :order="true"
        :selection="true"
      >
        <!-- <el-table-column type="index" width="50" /> -->
        <el-table-column label="帐户ID" prop="accountId" />
        <el-table-column label="用户名称" prop="accountName" />
        <el-table-column label="昵称" prop="nickName" />
        <el-table-column label="手机号" prop="phone" />
        <el-table-column label="所属角色" prop="roleNames" />
        <el-table-column label="随手拍数量" prop="snapshotAmout" />
        <el-table-column label="随手拍积分" prop="score" />
        <el-table-column label="注册时间" prop="createdTime" />
        <el-table-column label="状态" prop="status">
          <template slot-scope="scope">
            {{ renderOption(scope.row.status, "status") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180px">
          <template slot-scope="scope">
            <el-button type="text" @click="viewAuth(scope.row)" size="small">
              查看权限
            </el-button>
            <el-button
              type="text"
              @click="openUnionRole1(scope.row)"
              size="small"
            >
              关联角色
            </el-button>
            <el-button
              type="text"
              v-if="scope.row.status == 1"
              @click="edit(scope.row)"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              v-if="scope.row.status != 2"
              @click="handlerDelete(scope.row)"
              size="small"
            >
              删除
            </el-button>

            <el-button
              type="text"
              v-if="scope.row.status == 1 || scope.row.status == 2"
              @click="openResetDialog(scope.row)"
              size="small"
              >重置密码</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.status == 1"
              @click="lockAccount(scope.row)"
              size="small"
              >帐户冻结</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.status == 2"
              @click="unlockAccount(scope.row)"
              size="small"
              >帐户解冻</el-button
            >
          </template>
        </el-table-column>
      </edu-table>
    </div>

    <!-- 新增 编辑 -->
    <edu-dialog
      :title.sync="dialogConfig.title"
      :visible.sync="dialogConfig.showDialog"
      @close="closeDialog(dialogConfig)"
      width="800px"
    >
      <el-form
        ref="dialogForm"
        :model="dialogConfig.formData"
        :rules="dialogConfig.action === 'view' ? {} : dialogConfig.rules"
        label-width="100px"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="accountName">
              <el-input v-model="dialogConfig.formData.accountName" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="dialogConfig.formData.password"
                clearable
                type="password"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="dialogConfig.formData.nickName" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="dialogConfig.formData.phone" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="dialogConfig.formData.email" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区" prop="region">
              <QueryRegionTree
                v-model="dialogConfig.formData.region"
                :regionName="dialogConfig.formData.regionName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="dialogConfig.formData.description" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="头像" prop="photo">
              <Upload
                v-model="dialogConfig.formData.photo"
                ref="uploadComp"
                listType="picture-card"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属角色" prop="roleIdList">
              <DictSelect
                v-model="dialogConfig.formData.roleIdList"
                :url="api.queryRoleList"
                cacheValue="roleIdList"
                multiple
                placeholder="请选择"
                :valueFormat="
                  (item) => {
                    return item.roleId;
                  }
                "
                :labelFormat="
                  (item) => {
                    return item.roleName;
                  }
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dialogConfig.action === 'add'">
            <el-form-item label="状态" prop="status">
              <DictSelect
                v-model="dialogConfig.formData.status"
                :defaultOptions="options.status"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="buttons" v-if="dialogConfig.action !== 'view'">
        <template>
          <el-button @click="closeDialog(dialogConfig)"> 取消 </el-button>
          <el-button type="primary" @click="handlerSubmit"> 提交 </el-button>
        </template>
      </span>
      <span slot="buttons" v-else>
        <template>
          <el-button @click="closeDialog(dialogConfig)">返回</el-button>
        </template>
      </span>
    </edu-dialog>

    <!-- 重置密码 -->
    <ResetPass ref="resetPass" />
    <!-- 关联角色 -->
    <UnionRole ref="unionRole" @done="query" />
    <!-- 查看权限 -->
    <ViewAuth ref="viewAuth" @done="query" />
  </div>
</template>

<script>
import md5 from "md5";

import {
  queryAccountList,
  queryRoleList,
  addAccount,
  updateAccount,
  deleteAccount,
  queryAccountDetail,
  lockAccount,
  unlockAccount,
  exportAccount,
} from "@/api/users";

import mixins from "@/mixins";
import utils from "@/utils";
import ResetPass from "./components/ResetPass";
import UnionRole from "./components/UnionRole";
import ViewAuth from "./components/ViewAuth";

const formData = {
  accountName: "",
  phone: "",
  email: "",
  password: "",
  roleIdList: [],
  status: "",
  systemId: "100000001",
};
export default {
  mixins: [mixins],
  components: {
    ResetPass,
    UnionRole,
    ViewAuth,
  },
  data() {
    return {
      queryParams: {
        condition: {},
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableList: [],
      dialogConfig: {
        title: "",
        showDialog: false,
        action: "add",
        formData: {},
        rules: {
          accountName: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
          phone: [
            {
              required: true,
              validator: this.checkPhone,
              trigger: "blur",
            },
          ],
          email: [
            {
              // required: true,
              validator: this.checkEmail,
              trigger: "blur",
            },
          ],
          status: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
          password: [
            {
              required: true,
              validator: this.checkPassword,
              trigger: "blur",
            },
          ],
          roleIdList: {
            required: true,
            message: "此项必填！",
            trigger: "blur",
          },
        },
        fileList: [],
      },
      options: {
        roleIdList: "",
        status: [
          {
            name: "正常",
            code: 1,
          },
          {
            name: "账户冻结",
            code: 2,
          },
        ],
      },
      api: {
        queryRoleList: queryRoleList,
      },
    };
  },
  created() {
    this.initOptions();
  },
  methods: {
    checkPhone(rule, value, callback) {
      let regExp = /^1[23456789]\d{9}$/;
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (!regExp.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    },
    checkEmail(rule, value, callback) {
      if (value) {
        let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        if (!reg.test(value)) {
          return callback(new Error("请输入正确的邮箱"));
        }
      }
      return callback();
    },
    checkPassword(rule, value, callback) {
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (value.length < 6) {
        callback(new Error("密码须大于6位！"));
      } else {
        callback();
      }
    },
    async initOptions() {},
    // 查询
    async query(pageNum) {
      // 有pageNum 重置为第一页
      if (pageNum) {
        this.queryParams.pageNum = pageNum;
      }

      this.queryParams.condition.systemId = "100000001";
      let queryParams = utils.clone(this.queryParams);
      queryParams.condition.roleId = queryParams.condition.roleId
        ? queryParams.condition.roleId.toString()
        : "";
      let { returnObj } = await queryAccountList(queryParams);
      this.tableList = returnObj.list;
      this.queryParams.total = returnObj.total;
      this.queryParams.pageSize = returnObj.pageSize;
    },
    // 重置
    reset() {
      for (var key in this.queryParams.condition) {
        this.queryParams.condition[key] = "";
      }
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;

      this.query();
    },
    // 分页
    handleCurrentChange(row) {
      this.queryParams.pageSize = row.pageSize;
      this.queryParams.pageNum = row.pageNum;

      this.query();
    },
    closeDialog(dialog) {
      dialog.showDialog = false;

      this.$refs["dialogForm"].resetFields();
    },
    openDialog(dialog) {
      dialog.showDialog = true;
    },
    // 新增
    add() {
      this.dialogConfig.title = "新增";
      this.dialogConfig.action = "add";
      this.dialogConfig.formData = {};
      this.dialogConfig.formData = utils.clone(formData);

      this.openDialog(this.dialogConfig);
      this.$nextTick(() => {
        this.$refs.uploadComp.init();
      });
    },
    // 修改
    async edit(row) {
      this.dialogConfig.title = "编辑";
      this.dialogConfig.action = "edit";

      let { returnObj } = await queryAccountDetail(row.accountId);

      // 角色id转移成组件可使用的
      let roleIdList = [];
      returnObj.roleList.map((role) => {
        roleIdList.push(role.roleId);
      });

      this.dialogConfig.formData = utils.clone({
        ...returnObj,
        roleIdList: roleIdList,
        regionName: returnObj.extend.regionName,
      });

      this.openDialog(this.dialogConfig);
      this.$nextTick(() => {
        this.$refs.uploadComp.init();
      });
    },
    // 保存提交
    handlerSubmit() {
      let params = {
        ...this.dialogConfig.formData,
        password: md5(this.dialogConfig.formData.password),
      };
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if (this.dialogConfig.action == "add") {
            addAccount(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          } else {
            updateAccount(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          }
        }
      });
    },
    timeChange(date) {
      if (date) {
        this.queryParams.condition.beginTime = utils
          .dayjsIns(date[0])
          .format("YYYY/MM/DD HH:mm:ss");
        this.queryParams.condition.endTime = utils
          .dayjsIns(date[1])
          .format("YYYY/MM/DD HH:mm:ss");
      } else {
        this.queryParams.condition.beginTime = null;
        this.queryParams.condition.endTime = null;
      }
    },
    // 查看
    view() {
      this.dialogConfig.title = "查看";
      this.dialogConfig.action = "view";
      this.openDialog(this.dialogConfig);
    },
    // 查看权限
    viewAuth(row) {
      this.$refs.viewAuth.open(row);
    },
    // 打开重置密码
    openResetDialog(row) {
      this.$refs.resetPass.open(row);
    },
    // 打开关联角色
    openUnionRole(row) {
      let ids;
      if (!row.id) {
        ids = this.$refs.mainTable.getCheckData().map((c) => c.accountId);
      } else {
        ids = [row.id];
      }

      if (!ids || ids.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择",
        });
        return;
      }

      this.$refs.unionRole.open(ids);
    },
    openUnionRole1(row) {
      let ids;
      if (!row.id) {
        ids = this.$refs.mainTable.getCheckData().map((c) => c.accountId);
      } else {
        ids = [row.id];
      }
      this.$refs.unionRole.open(ids);
    },
    // 文件上传
    // handleChange(file) {
    //   const isLt2M = file.size / 1024 / 1024 < 5
    //   if (!isLt2M) {
    //     this.$message.error("上传文件大小不能超过 5MB!")
    //     this.clearFiles()
    //     return false
    //   }
    //   const types = [".jpg", ".png"]

    //   let postion = file.name.lastIndexOf(".")
    //   let prefix = file.name.substr(postion, file.name.length)

    //   if (!types.includes(prefix)) {
    //     this.$message.error("上传文件格式必须是.jpg或.png")
    //     this.clearFiles()
    //     return false
    //   }
    // },
    // handleSuccess(res, file, fileList) {
    //   if (res.success) {
    //     this.$message({
    //       type: "success",
    //       message: "上传成功"
    //     })

    //     this.dialogConfig.formData.image = res.returnObj
    //   } else {
    //     this.$message({
    //       duration: 5000,
    //       type: "error",
    //       message: "上传失败"
    //     })
    //     this.clearFiles()
    //   }
    // },
    // clearFiles() {
    //   if (this.$refs.upload) this.$refs.upload.clearFiles()
    // },
    // 文件上传end
    // 冻结
    async lockAccount(row) {
      this.$confirm(`确认冻结?`).then(() => {
        lockAccount([row.accountId]).then((res) => {
          this.$message({
            type: "success",
            message: "冻结成功",
          });
          this.query();
        });
      });
    },
    // 取消冻结
    async unlockAccount(row) {
      unlockAccount([row.accountId]).then((res) => {
        this.$message({
          type: "success",
          message: "取消冻结成功",
        });
        this.query();
      });
    },
    // 删除
    async handlerDelete(row) {
      let idField = "accountId";
      if (row && row[idField]) {
        this.batchDelete(deleteAccount, idField, [row[idField]]);
      } else {
        this.batchDelete(deleteAccount, idField);
      }
    },
    exportExcel() {
      let selectedIds = this.$refs.mainTable.getCheckData().map((item) => {
        return item.accountId;
      });
      exportAccount({
        idList: selectedIds,
        systemId: this.queryParams.condition.systemId,
        accountName: this.queryParams.condition.accountName,
        phone: this.queryParams.condition.phone,
        beginTime: this.queryParams.condition.beginTime,
        endTime: this.queryParams.condition.endTime,
        roleId: this.queryParams.condition.roleId
          ? this.queryParams.condition.roleId.toString()
          : "",
        status: this.queryParams.condition.status,
      }).then((res) => {
        utils.downloadFile(res);
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
